import * as echarts from '../../../components/ec-canvas/echarts';
const finance = require('../../../utils/finance');
const financeBill = require('../../../utils/finance-bill');
const app = getApp();

let that
Page({
  data: {
    yearMonth: '',
    income: 8000,
    expense: 5200,
    balance: 2800,
    // 账户相关
    accountList: [],
    accountIndex: 0,
    selectedAccount: null,
    // 饼状图配置项
    expensePieOpt: {
      lazyLoad: true
    },
    incomePieOpt: {
      lazyLoad: true
    },
    // 消费趋势图
    expenseLineOpt: {
      lazyLoad: true
    },
    // 收入趋势图
    incomeLineOpt: {
      lazyLoad: true
    },
    // 分类排行
    categoryList: [],
    showAccountSelector: false
  },
  async onLoad() {
    that = this;
    // 账户数据
    const { accountList, accountIndex } = await app.getAccountGlobal();
    this.setData({
      accountList,
      accountIndex,
      selectedAccount: accountList[accountIndex] || null
    });
    // 赋值yearMonth为当前年月
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    this.setData({ yearMonth: `${year}-${month}` }, async () => {
      await this.fetchStatisticsAndInit();
    });
  },
  async onAccountChange(e) {
    const idx = e.detail.value;
    const account = this.data.accountList[idx];
    this.setData({
      accountIndex: idx,
      selectedAccount: account
    });
    await this.fetchStatisticsAndInit();
  },
  async onMonthChange(e) {
    const yearMonth = e.detail.value;
    this.setData({ yearMonth });
    await this.fetchStatisticsAndInit(); // 重新请求/刷新数据
  },
  async fetchStatisticsAndInit() {
    const { yearMonth, selectedAccount } = this.data;
    if (!yearMonth || !selectedAccount) return;
    wx.showLoading({ title: '加载中...', mask: true });
    try {
      const res = await financeBill.getMonthStatistics({
        accountBookId: selectedAccount.id,
        yearMonth
      });
      wx.hideLoading();
      if (res) {
        this.initPageData(res || {});
      } else {
        wx.showToast({ title: (res && res.msg) || '获取统计失败', icon: 'none' });
        this.initPageData({});
      }
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title: (e && e.data && e.data.msg) || '获取统计失败', icon: 'none' });
      this.initPageData({});
    }
  },
  async initPageData(statData = {}) {
    // 这里根据statData填充图表和分类排行
    const income = statData.incomeAmount || 0;
    const expense = statData.expenseAmount || 0;
    const balance = statData.balanceAmount || 0;
    const expenseCategoryItems = statData.expenseCategoryItems || [];
    const incomeCategoryItems = statData.incomeCategoryItems || [];
    const expenseAmountItems = statData.expenseAmountItems || [];
    const incomeAmountItems = statData.incomeAmountItems || [];
    
    // 支出分类分布饼图
    this.selectComponent('#expensePie').init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
      canvas.setChart(chart);
      chart.setOption({
        title: { show: false, fontSize: 100, },
        legend: { top: 0, left: 'left', type: 'scroll' },
        tooltip: { 
          trigger: 'item' ,
          position: ['10%', '10%'] 
        },
        label: {
          show: false,
          position: 'left'
        },
        series: [{
          name: '',
          type: 'pie',
          radius: '70%',
          data: expenseCategoryItems,
          labelLine:{
            show: false
          },
          label:{
            show: false
          }
        }]
      });
      // 新增：点击事件，跳转到search页面
      chart.on('click', function(params) {
        wx.navigateTo({
          url: `/pages/finance/search/search?category=${encodeURIComponent(params.name)}&yearMonth=${that.data.yearMonth}&accountId=${that.data.selectedAccount.id}&type=expense`
        });
      });
      return chart;
    });

    // 收入分类分布饼图
    this.selectComponent('#incomePie').init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
      canvas.setChart(chart);
      chart.setOption({
        title: { show: false, fontSize: 100, },
        legend: { top: 0, left: 'left', type: 'scroll' },
        tooltip: { 
          trigger: 'item' ,
          position: ['10%', '10%'] 
        },
        label: {
          show: false,
          position: 'left'
        },
        series: [{
          name: '',
          type: 'pie',
          radius: '70%',
          data: incomeCategoryItems,
          labelLine:{
            show: false
          },
          label:{
            show: false
          }
        }]
      });
      // 新增：点击事件，跳转到search页面
      chart.on('click', function(params) {
        wx.navigateTo({
          url: `/pages/finance/search/search?category=${encodeURIComponent(params.name)}&yearMonth=${that.data.yearMonth}&accountId=${that.data.selectedAccount.id}&type=income`
        });
      });
      return chart;
    });
    if (expenseAmountItems.length){
      const expenseXAxisData = expenseAmountItems.map(item => item.date || item.day || '');
      // 支出趋势图
      this.selectComponent('#expenseLine').init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
        canvas.setChart(chart);
        chart.setOption({
          tooltip: { trigger: 'axis' },
          xAxis: { type: 'category', data: expenseXAxisData },
          yAxis: { type: 'value' },
          series: [{
            name: '支出',
            type: 'line',
            data: expenseAmountItems.map(item => item.amount || 0),
            smooth: true,
            areaStyle: { color: '#1976d2', opacity: 0.1 },
            lineStyle: { color: '#1976d2' }
          }]
        });
        return chart;
      });
    }

    const incomeXAxisData = incomeAmountItems.length > 0 ? incomeAmountItems.map(item => item.date || item.day || '') : [];
    // 收入趋势图
    this.selectComponent('#incomeLine').init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
      canvas.setChart(chart);
      chart.setOption({
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: incomeXAxisData },
        yAxis: { type: 'value' },
        series: [{
          name: '收入',
          type: 'line',
          data: incomeAmountItems.length > 0 ? incomeAmountItems.map(item => item.amount || 0) : [2000, 0, 0, 1000, 0, 2000, 1000],
          smooth: true,
          areaStyle: { color: '#43a047', opacity: 0.1 },
          lineStyle: { color: '#43a047' }
        }]
      });
      return chart;
    });


    // 分类排行
    const categoryList = expenseCategoryItems.length > 0 ? expenseCategoryItems.map(item => ({
      name: item.name || '未知',
      amount: item.value || 0,
      percent: item.percent || 0
    })).sort((a, b) => b.amount - a.amount) : [];
  
    that.setData({
      income,
      expense,
      balance,
      categoryList
    })
  },
  clickShowAccountSelector() {
    this.setData({ showAccountSelector: true });
  },
  async onSelectAccount(e) {
    const idx = e.detail.index;
    // 复用原有onAccountChange逻辑
    await this.onAccountChange({ detail: { value: idx } });
  }
});



